package traer.physics;

/**
 * @author Jeffrey Traer Bernstein, modifications by Roland Haring <P>
 * <a href="http://www.cs.princeton.edu/~traer/physics/" target="blank">http://www.cs.princeton.edu/~traer/physics/</a>
 */
public class ModifiedEulerIntegrator implements Integrator {

    ParticleSystem s;

    public ModifiedEulerIntegrator(ParticleSystem s) {
        this.s = s;
    }

	public void step(float _deltaT) {
        if (_deltaT==0) {
            return;
        }

        // this value here is inverted
        float deltaT = 1.0f / _deltaT;

        deltaT = 1.0f;

        s.clearForces();
        s.applyForces();

        float halftt = 0.5f * deltaT * deltaT;

        for (int i = 0; i < s.numberOfParticles(); i++) {
            Particle p = s.getParticle(i);
            p.age += _deltaT;
            if (p.isFree()) {
                float ax = p.force().x() / p.mass();
                float ay = p.force().y() / p.mass();
                float az = p.force().z() / p.mass();

                p.position().add(p.velocity().x() / deltaT * _deltaT, p.velocity().y() / deltaT * _deltaT, p.velocity().z() / deltaT * _deltaT);
                p.position().add(ax * halftt * _deltaT, ay * halftt * _deltaT, az * halftt * _deltaT);
                p.velocity().add(ax / deltaT * _deltaT, ay / deltaT * _deltaT, az / deltaT * _deltaT);
            }
        }
    }
}
